<template>
  <div class="service-management-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <span class="status-text">12:00</span>
      <div class="status-icons">
        <span class="icon">📶</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 头部导航 -->
    <div class="service-header">
      <button class="back-btn" @click="$router.back()">← 返回</button>
      <h2 class="header-title">客服管理</h2>
      <div class="header-right">
        <div class="connection-status" :class="{ connected: serviceWsConnected }">
          <span class="status-dot"></span>
          {{ serviceWsConnected ? '在线' : '离线' }}
        </div>
      </div>
    </div>

    <!-- 主内容区：左边栏 + 聊天区 -->
    <div class="main-content">
      <!-- 左边栏：在线用户列表 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h3>在线用户 ({{ consultationList.length }})</h3>
        </div>
        <div class="consultation-list">
          <div 
            v-for="consultation in consultationList" 
            :key="consultation.room_id"
            :class="['consultation-item', { active: currentRoomId === consultation.room_id }]"
            @click="enterChatRoom(consultation)"
          >
            <div class="avatar">
              <span>👤</span>
            </div>
            <div class="info">
              <div class="name">用户 {{ consultation.user_id }}</div>
              <div class="time">{{ formatTime(consultation.created_at) }}</div>
              <div class="status" :class="consultation.status">
                {{ getStatusText(consultation.status) }}
              </div>
            </div>
          </div>
          <div v-if="consultationList.length === 0" class="empty-tip">
            <p>暂无用户咨询</p>
            <p class="tip">等待用户发起咨询...</p>
          </div>
        </div>
      </div>

      <!-- 右侧：聊天区域 -->
      <div class="chat-area">
        <div v-if="!currentRoomId" class="welcome-screen">
          <div class="welcome-icon">👨‍💼</div>
          <h3>客服工作台</h3>
          <p>点击左侧用户进入对话</p>
        </div>

        <div v-else class="chat-room">
          <!-- 聊天室头部 -->
          <div class="chat-header">
            <div class="chat-title">
              <span class="avatar-small">👤</span>
              <span>与用户 {{ currentUserId }} 对话</span>
            </div>
            <div class="connection-status" :class="{ connected: chatRoomConnected }">
              <span class="status-dot"></span>
              {{ chatRoomConnected ? '已连接' : '连接中...' }}
            </div>
          </div>

          <!-- 消息列表 -->
          <div class="messages-container" ref="messagesContainer">
            <div 
              v-for="(message, index) in chatMessages" 
              :key="index"
              :class="['message-item', message.type]"
            >
              <div class="avatar">
                <span v-if="message.type === 'user'">👤</span>
                <span v-else>👨‍💼</span>
              </div>
              <div class="message-content">
                <div class="message-bubble" :class="message.type">
                  <p>{{ message.content }}</p>
                </div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>
            <div v-if="chatLoading" class="typing-indicator">
              <span></span><span></span><span></span>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <input 
              v-model="inputText"
              type="text"
              placeholder="输入回复..."
              class="message-input"
              @keyup.enter="sendMessage"
              :disabled="!chatRoomConnected"
            />
            <button 
              class="send-btn" 
              @click="sendMessage" 
              :disabled="!inputText.trim() || !chatRoomConnected || chatLoading"
            >
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据状态
const consultationList = ref([])
const currentRoomId = ref(null)
const currentUserId = ref(null)
const chatMessages = ref([])
const inputText = ref('')
const chatLoading = ref(false)
const serviceWsConnected = ref(false)
const chatRoomConnected = ref(false)

// WebSocket连接
const serviceWs = ref(null)
const chatRoomWs = ref(null)
const messagesContainer = ref(null)
const serviceId = 'service_1001' // 客服ID（可以改成动态的）

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    accepted: '进行中',
    rejected: '已拒绝',
    completed: '已结束'
  }
  return statusMap[status] || '未知'
}

// 进入聊天室
const enterChatRoom = async (consultation) => {
  currentRoomId.value = consultation.room_id
  currentUserId.value = consultation.user_id
  
  // 如果状态是pending，先接受咨询
  if (consultation.status === 'pending') {
    acceptConsultation(consultation.room_id)
  }
  
  // 清空当前聊天消息
  chatMessages.value = []
  
  // 连接到聊天室
  await connectToChatRoom(consultation.room_id, serviceId, 'service')
}

// 接受咨询
const acceptConsultation = (roomId) => {
  if (serviceWs.value && serviceWs.value.readyState === WebSocket.OPEN) {
    serviceWs.value.send(JSON.stringify({
      type: 'accept_consultation',
      room_id: roomId
    }))
    
    // 更新列表中的状态
    const consultation = consultationList.value.find(item => item.room_id === roomId)
    if (consultation) {
      consultation.status = 'accepted'
    }
  }
}

// 连接到聊天室
const connectToChatRoom = async (roomId, clientId, identity) => {
  return new Promise((resolve, reject) => {
    try {
      // 关闭旧的连接
      if (chatRoomWs.value) {
        chatRoomWs.value.close()
      }
      
      chatRoomConnected.value = false
      
      const wsUrl = `ws://127.0.0.1:8000/ws/chat/${roomId}`
      const ws = new WebSocket(wsUrl)
      
      ws.onopen = () => {
        console.log('[聊天室] 连接成功:', roomId)
        
        // 发送身份标识
        ws.send(JSON.stringify({
          identity: identity,
          client_id: clientId
        }))
        
        chatRoomWs.value = ws
        chatRoomConnected.value = true
        resolve(ws)
      }
      
      ws.onmessage = (event) => {
        const message = JSON.parse(event.data)
        console.log('[聊天室] 收到消息:', message)
        
        if (message.type === 'chat') {
          // 聊天消息
          chatMessages.value.push({
            type: message.sender === clientId ? 'service' : 'user',
            content: message.content,
            time: message.timestamp ? new Date(message.timestamp).toLocaleTimeString('zh-CN', { 
              hour: '2-digit', 
              minute: '2-digit' 
            }) : getCurrentTime()
          })
          
          chatLoading.value = false
          nextTick(() => scrollToBottom())
        } else if (message.type === 'user_joined' || message.type === 'service_joined') {
          // 对方进入
          chatMessages.value.push({
            type: 'system',
            content: '对方已进入聊天室',
            time: getCurrentTime()
          })
          nextTick(() => scrollToBottom())
        }
      }
      
      ws.onerror = (error) => {
        console.error('[聊天室] 连接错误:', error)
        chatRoomConnected.value = false
        reject(error)
      }
      
      ws.onclose = () => {
        console.log('[聊天室] 连接关闭')
        chatRoomConnected.value = false
        chatRoomWs.value = null
      }
      
    } catch (error) {
      console.error('[聊天室] 连接失败:', error)
      reject(error)
    }
  })
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || !chatRoomConnected.value || chatLoading.value) return
  
  const content = inputText.value.trim()
  
  // 添加到消息列表
  chatMessages.value.push({
    type: 'service',
    content: content,
    time: getCurrentTime()
  })
  
  inputText.value = ''
  chatLoading.value = true
  
  await nextTick()
  scrollToBottom()
  
  // 发送到聊天室
  if (chatRoomWs.value && chatRoomWs.value.readyState === WebSocket.OPEN) {
    chatRoomWs.value.send(JSON.stringify({
      type: 'chat',
      content: content,
      sender: serviceId
    }))
    chatLoading.value = false
  } else {
    chatLoading.value = false
    alert('连接已断开，请重新进入聊天室')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 初始化客服WebSocket（接收咨询请求）
const initServiceWebSocket = () => {
  try {
    const wsUrl = `ws://127.0.0.1:8000/ws/service/${serviceId}`
    const ws = new WebSocket(wsUrl)
    
    ws.onopen = () => {
      console.log('[客服WebSocket] 连接成功')
      serviceWs.value = ws
      serviceWsConnected.value = true
    }
    
    ws.onmessage = (event) => {
      const message = JSON.parse(event.data)
      console.log('[客服WebSocket] 收到消息:', message)
      
      if (message.type === 'new_consultation') {
        // 新咨询请求
        const data = message.data
        const existing = consultationList.value.find(item => item.room_id === data.room_id)
        if (!existing) {
          consultationList.value.push({
            ...data,
            avatar: null,
            lastMessage: null,
            unreadCount: 0
          })
        }
      } else if (message.type === 'consultation_list') {
        // 已有咨询列表（连接时发送）
        consultationList.value = message.data.map(item => ({
          ...item,
          avatar: null,
          lastMessage: null,
          unreadCount: 0
        }))
      }
    }
    
    ws.onerror = (error) => {
      console.error('[客服WebSocket] 错误:', error)
      serviceWsConnected.value = false
    }
    
    ws.onclose = () => {
      console.log('[客服WebSocket] 连接关闭')
      serviceWs.value = null
      serviceWsConnected.value = false
    }
    
  } catch (error) {
    console.error('[客服WebSocket] 初始化失败:', error)
  }
}

// 生命周期
onMounted(() => {
  initServiceWebSocket()
  scrollToBottom()
})

onBeforeUnmount(() => {
  if (serviceWs.value) {
    serviceWs.value.close()
  }
  if (chatRoomWs.value) {
    chatRoomWs.value.close()
  }
})
</script>

<style scoped>
.service-management-container {
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background: white;
  font-size: 12px;
}

.status-icons {
  display: flex;
  gap: 5px;
}

.service-header {
  background: white;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
  padding: 5px 10px;
  color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
  flex: 1;
  text-align: center;
}

.header-right {
  width: 80px;
  display: flex;
  justify-content: flex-end;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #999;
}

.connection-status.connected {
  color: #28a745;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
}

.connection-status.connected .status-dot {
  background: #28a745;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.consultation-list {
  flex: 1;
  overflow-y: auto;
}

.consultation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s;
  border-bottom: 1px solid #f5f5f5;
}

.consultation-item:hover {
  background: #f5f5f5;
}

.consultation-item.active {
  background: #e3f2fd;
}

.consultation-item .avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.consultation-item .info {
  flex: 1;
  min-width: 0;
}

.consultation-item .name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.consultation-item .time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.consultation-item .status {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.consultation-item .status.pending {
  background: #fff3cd;
  color: #856404;
}

.consultation-item .status.accepted {
  background: #d4edda;
  color: #155724;
}

.empty-tip {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.empty-tip .tip {
  font-size: 12px;
  margin-top: 10px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.welcome-screen {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.welcome-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.welcome-screen h3 {
  margin: 0 0 10px 0;
  color: #666;
}

.welcome-screen p {
  margin: 0;
  font-size: 14px;
}

.chat-room {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.avatar-small {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background: #f5f5f5;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
  gap: 10px;
}

.message-item.service {
  flex-direction: row-reverse;
}

.message-item.system {
  justify-content: center;
  margin-bottom: 10px;
}

.message-item .avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
  background: #e3f2fd;
}

.message-item.service .avatar {
  background: #007AFF;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.message-item.service .message-content {
  align-items: flex-end;
}

.message-item.user .message-content {
  align-items: flex-start;
}

.message-item.system .message-content {
  align-items: center;
  max-width: 100%;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
}

.message-bubble.service {
  background: #007AFF;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-bubble.user {
  background: white;
  color: #333;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 4px;
}

.message-bubble.system {
  background: transparent;
  color: #999;
  font-size: 12px;
  padding: 4px 8px;
}

.message-time {
  font-size: 11px;
  color: #999;
  padding: 0 5px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
  padding: 10px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.input-area {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 15px;
  background: white;
  border-top: 1px solid #f0f0f0;
}

.message-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.message-input:focus {
  border-color: #007AFF;
}

.message-input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.send-btn {
  padding: 10px 20px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.send-btn:hover:not(:disabled) {
  background: #0056b3;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>

